package com.obligatorio.ejb;

import java.io.Serializable;

import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;

import org.apache.log4j.Logger;

/**
 * Session Bean implementation class NotificationUtils
 */
@Stateless
@LocalBean
public class NotificationUtils {

	private static final Logger log = Logger.getLogger(NotificationUtils.class
			.getName());

	@Resource(mappedName = "ConnectionFactory")
	private ConnectionFactory notificationQueueFactory;

	@Resource(name = "queue/NotificationQueue", mappedName = "queue/NotificationQueue")
	private Queue notificationQueue;

	/**
	 * Default constructor.
	 */
	public NotificationUtils() {
		// TODO Auto-generated constructor stub
	}

	private Message createJMSMessageForjmsNotificationQueue(Session session,
			Object messageData) throws JMSException {
		// Modified to use ObjectMessage instead
		ObjectMessage tm = session.createObjectMessage();
		tm.setObject((Serializable) messageData);
		return tm;
	}

	public void sendJMSMessageToNotificationQueue(Object messageData)
			throws JMSException {
		log.info("sendJMSMessageToNotificationQueue()");
		Connection connection = null;
		Session session = null;
		try {

			connection = notificationQueueFactory.createConnection();
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			MessageProducer messageProducer = session
					.createProducer(notificationQueue);
			messageProducer.send(createJMSMessageForjmsNotificationQueue(
					session, messageData));
		} catch (JMSException e) {
			log.error(e);
		} finally {
			if (connection != null) {
				connection.close();

			}
		}
	}
}
